'''
An RPG Modification for Source games using Source Python.

    Copyright (C) 2012 Steven Hartin

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Created on 3 Dec 2012

@author: Steven Hartin
@file: ../sourcerpg/logging/logging.py
'''

from time import strftime

from paths import LOG_PATH
from core.commands import echo_console

from sourcerpg.logging.consts import loglevels

__all__ = ["Logger"]


class Logger(object):
    """A class to handle the logging of messages to console / text files.

    The log levels are bitwise flags and allow us to specifically control
    which log messages are seen / received. Rather than have a default
    'level', we shall assign logs to have 'roles', not too dissimilar to
    the way PHP handles their error logs. The log permissions can be found
    in consts.py for the LoggingLevels enum. In short, the list of logging
    permissions can be seen as follows:

    loglevels.CRITICAL_ERROR
    loglevels.WARNING
    loglevels.DEBUG_TEXT
    loglevels.AUTOLOGGING

    loglevels.INFO_LEVEL_1
    loglevels.INFO_LEVEL_2
    loglevels.INFO_LEVEL_3
    loglevels.INFO_LEVEL_4

    """
    def __init__(self, loglevel=loglevels.DEFAULT):
        self.loglevel = loglevel

    def set_log_permision(self, logpermission):
        """Clears a permission from the current log level."""
        self.loglevel |= logpermission

    def clear_log_permission(self, logpermission):
        """Adds a permission to the current log level."""
        self.loglevel &= ~logpermission

    def log(self, text, level=loglevels.ALL, stdout=True, writetime=False,
            suffix='\n', prefix=''):
        """Logs a message to both a file and server console.

        @param str text The text to log
        @param LoggingLevels level The level of the logging, allows us to
            control which messages are 'seen' depending on the permission of
            the level.
        @param IO stdout Any file handle to redirect the logging to. NB, this
            does NOT close the file, that must be handled by the caller. Valid
            values are as follows:
            True - Use the 'default' log file (sourcerpg.log)
            None/False/0 - Do not print to a file
            Any other valid IO format with a 'write' function
        @param bool writetime Whether or not to prefix a time (HH:MM:SS format)
        @param str suffix A suffix for the text
        @param str prefix A prefix for the text

        """
        # The levels are bitwise flags, test to see if we have permission
        if self.loglevel & level:
            if writetime is True:
                text = "%s - %s" % (strftime("%H:%M:%S"), text)
            text = "%s%s%s" % (prefix, text, suffix)
            if stdout not in (None, False, 0):
                handle = stdout
                if stdout is True:
                    handle = open(LOG_PATH.joinpath("sourcerpg.log"), "a")
                handle.write(text)
                if stdout is True:
                    handle.close()
            # Strip end of line characters, engine does this for us.
            echo_console(text.rstrip("\n"))
